package com.ionicframework.esayparking199835.wxapi;

import android.app.Activity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;

import com.ionicframework.esayparking199835.DataWX;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Jay on 2016/8/2.
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler{

  private IWXAPI api;
  private static final String APP_ID = "wx12a436a427994b98";
  private static final String APP_SECRET = "e3704af4c67ff62a1c9c1cdaed6d2fea";


  private String Access_Token = null;
  private String Refresh_Token;
  private String OPENID;
  private String UNIONID;
  private Integer Expires_In;
  private String NICKNAME;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //api注册
    api = WXAPIFactory.createWXAPI(this, APP_ID, true);
    api.registerApp(APP_ID);
  }

  @Override
  public void onReq(BaseReq baseReq) {

  }

  @Override
  public void onResp(BaseResp resp) {
    if (resp instanceof SendAuth.Resp) {
      SendAuth.Resp newResp = (SendAuth.Resp) resp;

      //获取微信传回的code
      String code = newResp.code;
      Log.i("code", "###########################" + newResp.code);

      //根据传回的code获取Access_token
      getToken(code);

      //根据传回的Access_token和Openid获取用户信息
      //getUserInfo(Access_Token,OPENID);

    }
  }

  public void getToken(final String code) {
    new Thread() {
      @Override
      public void run() {
        try {
          URL url = new URL("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID
            + "&secret=" + APP_SECRET + "&code=" + code + "&grant_type=authorization_code");

          HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
          urlConnection.connect();

          InputStream is = new BufferedInputStream(urlConnection.getInputStream());
          InputStreamReader isr = new InputStreamReader(is);

          //转为json格式
          JsonReader jsonReader = new JsonReader(isr);

          jsonReader.beginObject();
          while (jsonReader.hasNext()) {
            String name = jsonReader.nextName();
            if (name.equals("access_token")) {
              Access_Token = jsonReader.nextString();
              Log.i("code", "+++++++++++++++++++++++access_token" + Access_Token);
            } else if (name.equals("expires_in")) {
              Expires_In = jsonReader.nextInt();
              Log.i("code", "+++++++++++++++++++++++expires_in" + Expires_In);
            } else if (name.equals("refresh_token")) {
              Refresh_Token = jsonReader.nextString();
              Log.i("code", "+++++++++++++++++++++++refresh_token" + Refresh_Token);
            } else if (name.equals("openid")) {
              OPENID = jsonReader.nextString();
              Log.i("code", "+++++++++++++++++++++++openid" + OPENID);
            } else if (name.equals("unionid")) {
              UNIONID = jsonReader.nextString();
              Log.i("code", "+++++++++++++++++++++++unionid" + UNIONID);
            } else {
              jsonReader.skipValue();
            }
          }

          //根据传回的Access_token和Openid获取用户信息
          getUserInfo(Access_Token, OPENID);


          Log.i("code", "=============================");
          urlConnection.disconnect();

        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }.start();
  }

  public void getUserInfo(final String AccessToken, final String Openid) {
    try {
      URL url = new URL("https://api.weixin.qq.com/sns/userinfo?access_token=" + AccessToken
        + "&openid=" + Openid);

      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.connect();

      InputStream is = new BufferedInputStream(urlConnection.getInputStream());
      InputStreamReader isr = new InputStreamReader(is);

      //转为json格式
      JsonReader jsonReader = new JsonReader(isr);

      jsonReader.beginObject();
      while (jsonReader.hasNext()) {
        String name = jsonReader.nextName();
        if (name.equals("nickname")) {
          NICKNAME = jsonReader.nextString();
          Log.i("code", "+++++++++++++++++++++++nickname" + NICKNAME);
          // Toast.makeText(this, NICKNAME, Toast.LENGTH_LONG).show();
        } else {
          jsonReader.skipValue();
        }
      }
      Log.i("code", "=============================");
      urlConnection.disconnect();

      DataWX.NICKNAME = NICKNAME;
      DataWX.UnionId = UNIONID;

     // WechatLogin.WechatLogin(DataWX.NICKNAME,WechatLogin.cbContext);

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
